package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.*;
import com.bwie.poi.ExcelUtil;
import com.bwie.pojo.*;
import com.bwie.service.TbOrderService;
import com.bwie.utils.Result;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author andy
* @description 针对表【tb_order(订单表)】的数据库操作Service实现
* @createDate 2025-05-30 09:27:47
*/
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{

    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpServletResponse response;

    @Autowired
    TbProdInfoMapper tbProdInfoMapper;

    @Autowired
    TbOrderMapper tbOrderMapper;

    @Autowired
    TbOrderDetailMapper tbOrderDetailMapper;

    @Autowired
    TbProdMapper tbProdMapper;

    @Autowired
    TbProdImageMapper tbProdImageMapper;

    @Autowired
    TbOrderRecordMapper tbOrderRecordMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addOrder(List<TbProdInfo> prodInfoList) {
        //--1 获取用户信息
        String token = request.getHeader("token");
        if(token == null) {
             return Result.error().setMsg("请先登录");
        }

        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        String userName = body.get("userName", String.class);
        String nickName = body.get("nickName", String.class);

        //--2 判断库存
        BigDecimal amount = new BigDecimal(0.0);
        StringBuilder nameList = new StringBuilder();
        Integer total = 0;
        for (TbProdInfo tbProdInfo : prodInfoList) {
            TbProdInfo prodInfo = tbProdInfoMapper.selectById(tbProdInfo.getInfoId());
            // 检查库存
            if(tbProdInfo.getBuyNum() > prodInfo.getProdStock()) {
                //return Result.error().setMsg("库存不足");
                throw new RuntimeException("库存不足");
            }
            else {
                // 扣减库存
                prodInfo.setProdStock( prodInfo.getProdStock() - tbProdInfo.getBuyNum());
                tbProdInfoMapper.updateById(prodInfo);
            }

            // 计算订单金额
            amount = prodInfo.getProdPrice().multiply(new BigDecimal(tbProdInfo.getBuyNum())).add(amount);

            // 连接商品名称
            TbProd tbProd = tbProdMapper.selectById(prodInfo.getProdId());
            if(nameList.length() == 0) {
                 nameList.append(tbProd.getProdName()).append(prodInfo.getAttrColor());
            }
            else {
                nameList.append(",").append(tbProd.getProdName()).append(prodInfo.getAttrColor());
            }

            // 计算商品数量
            total += tbProdInfo.getBuyNum();
        }


        //--3 创建订单
        TbOrder tbOrder = new TbOrder();
        tbOrder.setUserId( userId);
        tbOrder.setCreateBy(nickName);
        tbOrder.setCreateTime(new Date());

        // 雪花算法生成订单ID
        long orderNo = IdUtil.getSnowflake(1, 1).nextId();
        System.out.println("订单ID：" + orderNo);
        tbOrder.setOrderNo(orderNo);

        tbOrder.setOrderStatus(0);
        tbOrder.setAmount(amount);
        tbOrder.setOrderType(0);
        tbOrder.setCoupon(0);
        tbOrder.setDelivery("");

        // 设置购买商品的名称列表
        tbOrder.setProdInfo(nameList.toString());

        // 设置购买商品的数量
        tbOrder.setProdNum(total);

        tbOrder.setUseScore(0);

        // 保存订单
        tbOrderMapper.insert(tbOrder);


        //--4 创建订单详情
        for (TbProdInfo tbProdInfo : prodInfoList) {
            TbOrderDetail tbOrderDetail = new TbOrderDetail();
            tbOrderDetail.setOrderId(tbOrder.getOrderId());
            tbOrderDetail.setProdId(tbProdInfo.getProdId());
            tbOrderDetail.setProdNum( tbProdInfo.getBuyNum());
            tbOrderDetail.setProdPrice(tbProdInfo.getProdPrice());

            tbOrderDetailMapper.insert(tbOrderDetail);
        }

        //-5 新增订单记录
        TbOrderRecord tbOrderRecord = new TbOrderRecord();
        // 与订单ID关联
        tbOrderRecord.setOrderId(tbOrder.getOrderId());
        // 与商品ID关联
        Integer prodId = prodInfoList.get(0).getProdId();
        tbOrderRecord.setProdId(prodId);

        tbOrderRecord.setRecordContent("用户订单创建");
        tbOrderRecord.setCreateTime(new Date());
        tbOrderRecordMapper.insert(tbOrderRecord);


        return Result.ok();
    }

    @Override
    public Result getOrderList(PageInfoVo pageInfoVo) {
        //--1 构造分页参数
        Page<TbOrder> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        //--2 获取订单列表（分页查询）
//        QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();
//        wrapper.lambda().orderByDesc(TbOrder::getCreateTime);
//        Page<TbOrder> tbOrderPage = tbOrderMapper.selectPage(page, wrapper);
        Page<TbOrder> tbOrderPage = tbOrderMapper.getOrderList(page, pageInfoVo);

        tbOrderPage.getRecords().forEach( tbOrder -> {
            List<TbOrderDetail> tbOrderDetails = tbOrderDetailMapper.selectList(
                    new QueryWrapper<TbOrderDetail>().lambda().eq(TbOrderDetail::getOrderId, tbOrder.getOrderId())
            );

            tbOrderDetails.forEach( tbOrderDetail -> {
                List<TbProdImage> tbProdImages = tbProdImageMapper.selectList(
                        new QueryWrapper<TbProdImage>().lambda().eq(TbProdImage::getProdId, tbOrderDetail.getProdId())
                );

                // 使用stream流转为图片 列表
                List<String> imageList = tbProdImages.stream().map(item -> item.getImageUrl()).collect(Collectors.toList());

                // 设置 图片列表
                tbOrderDetail.setImageList(imageList);

                tbOrder.setImageList(imageList);
            });

            // 把 订单详情列表 设置到 订单对象中
            tbOrder.setOrderDetailList(tbOrderDetails);
        });


        //--3 返回订单列表
        return Result.ok().setData(tbOrderPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteAll(List<TbOrder> tbOrderList) {

        for (TbOrder tbOrder : tbOrderList) {
            //--1 判断订单是否存在
            TbOrder order = tbOrderMapper.selectById(tbOrder.getOrderId());
            if(order == null) {
                 throw new RuntimeException("订单不存在");
            }

            //--2 先删明细
            tbOrderDetailMapper.delete(
                    new QueryWrapper<TbOrderDetail>().lambda().eq(TbOrderDetail::getOrderId, tbOrder.getOrderId())
            );

            //--3 再删订单
            tbOrderMapper.deleteById(tbOrder.getOrderId());
        }

        return Result.ok();
    }

    @Override
    public void exportExcel(String ids) {
        // ids = 1,2,5
        String[] idList = ids.split(",");
        ArrayList<Integer> integers = new ArrayList<>();
         for (String id : idList) {
            integers.add(Integer.parseInt(id));
        }

         // 查询订单列表
        List<TbOrder> tbOrders = tbOrderMapper.selectBatchIds(integers);

         // 导出文件
        ExcelUtil<TbOrder> excelUtil = new ExcelUtil<>(TbOrder.class);
        excelUtil.exportExcel(response, tbOrders,  "订单列表");
    }
}




